package com.hehe.Tool;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

// LoginUtils.java
public class LoginUtils {

    private static final String SECRET_KEY = "your-very-secret-key"; // 放在配置文件更好

    // 创建 token
    public static String createToken(String userId, long expireTimestamp) {
        return userId + "." + expireTimestamp + "." + generateSignature(userId, expireTimestamp);
    }

    // 从 cookie 中提取 token
    public static String getTokenFromCookies(HttpServletRequest request) {
        if (request.getCookies() == null) return null;
        for (Cookie cookie : request.getCookies()) {
            if ("remember_token".equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    // 校验 token 并返回 userId
    public static String verifyTokenAndGetUserId(String token) {
        if (token == null || !token.contains(".")) return null;
        String[] parts = token.split("\\.");
        if (parts.length != 3) return null;

        String userId = parts[0];
        long expire;
        try {
            expire = Long.parseLong(parts[1]);
        } catch (NumberFormatException e) {
            return null;
        }
        String signature = parts[2];

        if (System.currentTimeMillis() > expire) return null;
        String validSig = generateSignature(userId, expire);
        if (!validSig.equals(signature)) return null;

        return userId;
    }

    // 签名算法
    private static String generateSignature(String userId, long expire) {
        try {
            String data = userId + expire + SECRET_KEY;
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 可选：尝试获取 userId，允许匿名访问逻辑
    public static String tryGetUserId(HttpServletRequest request) {
        String token = getTokenFromCookies(request);
        return verifyTokenAndGetUserId(token);
    }


    // 返回 userid
    public static String get_Logged_UserId(HttpServletRequest request) {
        return verifyTokenAndGetUserId(getTokenFromCookies(request));
    }




}
